package com.g2room.driving.grap.article;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.g2room.driving.util.DbUtil;
import com.g2room.driving.util.HtmlUtil;
import com.g2room.driving.util.ImageUtil;

public class HandleWeixinImages {
	public static void main(String[] args) {
		grapImg();
	}
	
	public static void grapImg() {
		int updateId = 2;
		Date d = DbUtil.getPublishTime(updateId);
		Map<String, String> imgs = getImageSrc(d);
		StringBuffer errSrcSb = new StringBuffer();
		int i = 0;
		for(String src : imgs.keySet()) {
			if((!src.startsWith("http://") 
				&& !src.startsWith("https://") )
				|| src.startsWith("http://www.g2room.com/images/")
				) {
				System.out.println("跳过====="+src);
				continue;
			}
			try {
				String filePath = ImageUtil.downloadImageByType(src, imgs.get(src));
				insertImg("update d_article_grap set content=replace(content,'"+src+"','"+filePath.replace(ImageUtil.folder, "http://www.kaichejiqiao.cn/images/")+"');");
				i++;
			} catch (Exception e) {
				System.out.println(src + "\n");
				e.printStackTrace();
			}
		}
		// 更新到抓取图片时间
		DbUtil.updateTime(updateId);
		DbUtil.closeConn();
		// 生成update语句
		System.out.println(i + "----------------------------------------------err is:");
		System.out.println(errSrcSb.toString());
		System.out.println(i + "----------------------------------------------update sql is:");
//		// 生成update语句
//		System.out.println(updateSqlSb.toString());
	}

	/**
	 * 获取所有的图片地址
	 */
	public static Map<String, String> getImageSrc(Date d) {
		Map<String, String> imgs = new HashMap<String, String>();
		try {
			Connection connection = DbUtil.getConn();
			Statement statement = connection.createStatement();
			String sql = "select content from d_article_grap where state=8 and create_time>'" + HtmlUtil.date2String(d, "yyyy-MM-dd hh:mm:ss")+"'";
			ResultSet rs = statement.executeQuery(sql);
			while(rs.next()) {
				String content = rs.getString("content");
				// 提取src值
				 imgs.putAll(getImgSrc(content));
			}
			rs.close();
			statement.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
		return imgs;
	}
	/**
	 * 提取图片的路径
	 * @param html	待提取的html内容
	 * @param srcField	图片标签属性
	 * @return
	 */
	public static Map<String, String> getImgSrc(String html) {
		Map<String, String> imgSrcs = new HashMap<String, String>(); 
		String regImg = "<img.*src\\s*=\\s*(.*?)[^>]*?>"; 
		Pattern p = Pattern.compile(regImg,Pattern.CASE_INSENSITIVE);
		Matcher matcher =  p.matcher(html);
		while(matcher.find()){
			String type = "";
			String srcUrl = "";
			String src = matcher.group();
			Matcher m  = Pattern.compile("data-src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(src);
            while(m.find()){
            	srcUrl = m.group(1);
            }
            Matcher t  = Pattern.compile("data-type\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(src);
            while(t.find()){
            	type = t.group(1);
            }
            if(null==type || type.length()==0) type = "jpeg";
            imgSrcs.put(srcUrl, type);
		}
		return imgSrcs;
	}
	
	public static void insertImg(String sql) {
		try {
			Connection connection = DbUtil.getConn();
			PreparedStatement statement = connection.prepareStatement("insert into d_images(updateSql) values(?)");
			statement.setString(1, sql);
			statement.execute();
			statement.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}
